<?php

namespace app\api\controller;

use app\common\controller\Api;
use Hedeqiang\TenIM\IM;
use think\Db;
use think\Cache;
/**
 * 虚拟测试接口
 */
class Xnpay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
     //        getUrl是在common中封装的，封装样式如下
     public function getUrl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }

    function calc_pay_sig($uri, $post_body, $appkey) {
        // pay_sig签名算法
        $need_sign_msg = $uri . '&' . $post_body;
        $pay_sig = hash_hmac('sha256', $need_sign_msg, $appkey);
        return $pay_sig;
    }
    function calc_signature($post_body, $session_key) {
        // 用户登录态signature签名算法
        $need_sign_msg = $post_body;
        $signature = hash_hmac('sha256', $need_sign_msg, $session_key);
        return $signature;
    }
    /**
     * 发送post请求
     */
    function json_post($url, $data = [])
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
//          $data = '{
//   "openid": "o5j2n6xk4LKaYLxS7Kg57FIJ_eCg",
//   "env": 0,
//   "user_ip": "112.32.95.206"
// }';
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json;',
            // 'Cache-Control: no-cache',
            // 'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;

    }
    
    //获取小程序二维码的token
    public function get_access_token()
    {
        //先判断缓存里面的access_token过期了没有
        if(Cache::get('access_token')){
            //没过期直接拿出来用
            $a = Cache::get('access_token');
            return $a;
        }else{
            //过期了就重新获取
            $appid = 'wxbae1b3248b60e1d8';
            $secret = 'b3df3f25537d5c1cdd9ac67e47b7391c';
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            
            //请求接口，获取accesstoken
            $user_obj = $this->curlHttp($url);
            //然后将accesstoken存入缓存里面，官方过期时间7200秒，缓存里面可以过期的早一点，自己把控
            Cache::set('access_token',$user_obj['access_token'],7100);

            return Cache::get('access_token');
        }
    }

    function curlHttp($url)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return json_decode($output, true);
    }
     /**
     * 测试一下
     * @param string $code  code
     */
    public function getEpisodeChapter()
    {
        $appID = 'wxbae1b3248b60e1d8';
        $appSecret = 'b3df3f25537d5c1cdd9ac67e47b7391c'; // 此处appkey为假设值，实际使用应根据支付环境(env参数)替换为对应的AppKey
        $appkey = "p0fJXLjHfnfJ2Imcya9dolUFuzIPwq1r";
        $code = input("code");
        //请求地址
        // $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appID."&secret=".$appSecret."&js_code=".$code."&grant_type=authorization_code";
        // // $res = $this->getUrl($url);
        // $res = array
        // (
        //     "session_key" => "IN6Y9HhKVS8yLHeIL9Bqqg==11",
        //     "openid" => "o5j2n6xk4LKaYLxS7Kg57FIJ_eCg"
        // );
        $user_find = DB::name("user")->where("id",146)->find();
        
        // //扣除虚拟支付的余额
        // $uri = '/xpay/currency_pay';
        // $data = array(
        //     "openid" => $user_find['openid'],
        //     "env" => 1,
        //     "user_ip" => $_SERVER['REMOTE_ADDR'],
        //     "amount" => 1,
        //     "order_id" => 'recharge202404180832019594',
        //     "payitem" => "testpayitem",
        //     "remark" => "testremark",
        //     "device_type" => 1,
        // );
        // // 
        // $post_body = json_encode($data);
        // $pay_sig = $this->calc_pay_sig($uri, $post_body, $appkey);
        // $access_token = $this->get_access_token();
        // $signature = $this->calc_signature($post_body, $user_find['session_key']);
        // // print_r($access_token);exit;
        // $url = 'https://api.weixin.qq.com/xpay/currency_pay?access_token='.$access_token.'&pay_sig='.$pay_sig.'&signature='.$signature;
        // $res = json_decode($this->json_post($url,$data),true);
        
        
        
        
        // print_r($res);exit;
        // 如果是基础库的wx.requestVirtualPayment，uri固定为requestVirtualPayment
        $uri = '/xpay/query_user_balance';
        // 此处appkey为假设值，实际使用应根据支付环境(env参数)替换为对应的AppKey
        $appkey = "p0fJXLjHfnfJ2Imcya9dolUFuzIPwq1r";
        // $appkey = "SgM7386iqymWi0qrj7ReIn7CbgRqLjBA";
        $order_id = date("YmdHis");
        // post_body参数
        // $user_find = DB::name("user")->where("id",$this->auth->id)->find();
        $ip = $_SERVER['REMOTE_ADDR'];
        $data = array(
            "openid" => $user_find['openid'],
            "env" => 1,
            "user_ip" => $ip
        );
        // 
        $post_body = json_encode($data);
        $pay_sig = $this->calc_pay_sig($uri, $post_body, $appkey);
        // $pay_sig =  bin2hex(hash_hmac('sha256',$post_body,$appkey,false));
        echo "pay_sig: " . $pay_sig . "\n";

        // session_key需要为当前用户有效session_key（参考auth.code2Session接口获取）
        // $session_key = "9hAb/NEYUlkaMBEsmFgzig==";
        $appID = 'wxbae1b3248b60e1d8';
        $appSecret = 'b3df3f25537d5c1cdd9ac67e47b7391c';
        // $code = input("code");
        //请求地址
        // $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appID."&secret=".$appSecret."&js_code=".$code."&grant_type=authorization_code";
        // $res = $this->getUrl($url);
        
        $signature = $this->calc_signature($post_body, $user_find['session_key']);
        // $signature =  bin2hex(hash_hmac('sha256',$post_body,$appkey,false));
        // echo "signature: " . $signature . "\n";

        $access_token = $this->get_access_token();
        // print_r($access_token);exit;
        $url = 'https://api.weixin.qq.com/xpay/query_user_balance?access_token='.$access_token.'&pay_sig='.$pay_sig;
        echo $url. "\n";
        
        
        $res = json_decode($this->json_post($url,$data),true);
        print_r($res);exit;

    }
    
    
}
